package com.yuhuihui.common.aop;

import com.yuhuihui.common.annotation.verify.NotNull;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Parameter;

/**
 * 验证切面
 *
 * @author yuhh
 * @date 2023-05-25 14:52:44
 */
@Aspect
public class VerifyAspect {

    @Pointcut("@annotation(com.yuhuihui.common.annotation.verify.Verify)")
    private void verify(){};

    @Before("verify()")
    public void verifyBefore(JoinPoint joinPoint){
        // 方法参数值
        Object[] args = joinPoint.getArgs();
        // 获取方法签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        // 获取方法参数对象
        Parameter[] parameters = methodSignature.getMethod().getParameters();
        Parameter parameter;
        for (int i = 0, size = args.length; i < size; i ++){
            parameter = parameters[i];
            if (parameter.isAnnotationPresent(NotNull.class) && ObjectUtils.isEmpty(args[i])){
                throw new RuntimeException(joinPoint.getTarget().getClass().getName() + "的方法" + methodSignature.getName() + "的参数" + parameter.getName() + "为null");
            }
        }
    }
}
